import { useCallback } from 'react'
import useAxios from 'axios-hooks'
import { axiosInstance } from './useAxios'

// GET 请求
export const useGet = (url: string, options?: any) => {
  return useAxios({
    url,
    method: 'GET',
    ...options,
  }, {
    manual: true,
    axios: axiosInstance,
  })
}

// POST 请求
export const usePost = (url: string, options?: any) => {
  return useAxios({
    url,
    method: 'POST',
    ...options,
  }, {
    manual: true,
    axios: axiosInstance,
  })
}

// 通用保存方法
export const useSave = (baseUrl: string) => {
  const [{ loading }, execute] = usePost(baseUrl)
  
  const save = useCallback(async (data: any) => {
    const url = data.id ? `${baseUrl}/${data.id}` : baseUrl
    const method = data.id ? 'PUT' : 'POST'
    return execute({ url, method, data })
  }, [baseUrl, execute])
  
  return { loading, save }
}

// 删除方法
export const useRemove = (baseUrl: string) => {
  const [{ loading }, execute] = useAxios({}, { manual: true, axios: axiosInstance })
  
  const remove = useCallback(async (id: string) => {
    return execute({
      url: `${baseUrl}/${id}`,
      method: 'DELETE',
    })
  }, [baseUrl, execute])
  
  return { loading, remove }
}

// 分页查询
export const usePage = (url: string, defaultParams = {}) => {
  const [{ data, loading, error }, refetch] = useAxios({
    url,
    method: 'GET',
    params: {
      page: 1,
      size: 10,
      ...defaultParams,
    },
  }, {
    axios: axiosInstance,
  })
  
  return {
    data: data?.content || [],
    total: data?.totalElements || 0,
    loading,
    error,
    refetch,
  }
}